#!/usr/bin/env python
# -*- coding: utf-8 -*-
# https://www.cnblogs.com/jmmchina/p/6692149.html
import time

import itchat
from itchat.content import TEXT, FRIENDS
from EmailUtil import sendmsg
from threading import Thread

def config():
    # 回复所有文本信息（不包括群聊）
    @itchat.msg_register(TEXT, isGroupChat=True)
    def text_reply(msg):
        itchat.send('%s: %s' % (msg['Type'], msg['Text']), msg['FromUserName'])


    # 收到好友邀请自动添加好友
    @itchat.msg_register(FRIENDS)
    def add_friend(msg):
        itchat.add_friend(**msg['Text'])  # 该操作会自动将新好友的消息录入，不需要重载通讯录
        itchat.send_msg('Nice to meet you!', msg['RecommendInfo']['UserName'])

if __name__ == "__main__":
    if itchat.load_login_status(fileDir="./itchat.pkl"):
        config()
        itchat.run()
        itchat.dump_login_status()
    else:
        t1= Thread(target=itchat.auto_login,kwargs={"hotReload":True})
        t1.setDaemon(True)
        t1.start()
        time.sleep(10)
        print("here")
        sendmsg("./QR.png")
        for i in range(5):
            if t1.is_alive() ==False:
                break
            time.sleep(60)
        else:
            raise Exception("login time out !")
        config()
        itchat.run()
        itchat.dump_login_status()
        print('Config stored, so exit.')

